<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\common\model\Admin;
use lib\Geetestlib;

class UserController extends Controller
{
    public function login(Request $request)
    {
        if(session('uid'))$this->redirect('index/index');
        return view();
    }
    public function  geettest(){
        /**
         * 使用Get的方式返回：challenge和capthca_id 此方式以实现前后端完全分离的开发模式 专门实现failback
         * @author Tanxu
         */
        $GtSdk = new GeetestLib(CAPTCHA_ID, PRIVATE_KEY);
        $data = array(
            "user_id" => "test", # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
        );
        $status = $GtSdk->pre_process($data, 1);
        session('gtserver',$status);
        session('user_id',$data['user_id']);
        echo $GtSdk->get_response_str();
    }

    public function VerifyLoginServlet(Request $request){
        /**
         * 输出二次验证结果,本文件示例只是简单的输出 Yes or No
         */
        $GtSdk = new GeetestLib(CAPTCHA_ID, PRIVATE_KEY);
        $data = array(
            "user_id" => session('user_id'), # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1", # 请在此处传输用户请求验证时所携带的IP
            "username"=>input('post.username/s'),
            "pwd" =>input('post.pwd/s'),
        );
        if ($_SESSION['gtserver'] == 1) {   //服务器正常
            $result = $GtSdk->success_validate($request->geetest_challenge, $request->geetest_validate, $request->geetest_seccode, $data);
            if ($result) {
                //处理登陆
                if($request->isPost()){
                    $username = $data['username'];
                    $pwd = $data['pwd'];
                    $user_info = Admin::where('user_name',$username)->find();
                    if($user_info){
                        if(md5(md5($pwd).$user_info['salt'])===$user_info['password']){
                            session('uid',$user_info['id']);
                            session('username',$user_info['user_name']);
                            ajaxReturn('登陆成功',1);
                        }else{
                            ajaxReturn('密码不正确',0);
                        }
                    }else{
                        ajaxReturn('用户名不存在',0);
                    }
                }
            } else{
                ajaxReturn('验证失败',0);
            }
        }else{  //服务器宕机,走failback模式
            if ($GtSdk->fail_validate($_POST['geetest_challenge'],$_POST['geetest_validate'],$_POST['geetest_seccode'])) {
                echo '{"status":"success"}';
            }else{
                echo '{"status":"fail"}';
            }
        }
    }


}
